package com.sky;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelDemo {
    public static void main(String[] args) throws Exception {
        //写
        //write();
        //读
        read();
    }

    private static void read() throws IOException {
        FileInputStream is = new FileInputStream(new File("D://poi_excel.xlsx"));
        XSSFWorkbook excel = new XSSFWorkbook(is);
        //获取第一页
        XSSFSheet sheetAt = excel.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheetAt.getLastRowNum();
        for (int i = 0; i <= lastRowNum; i++) {
            XSSFRow row = sheetAt.getRow(i);
            //第二个单元格
            String cellValue1 = row.getCell(1).getStringCellValue();
            //第三个单元格
            String cellValue2 = row.getCell(2).getStringCellValue();
            System.out.println(cellValue1+" "+cellValue2);
        }
        //关闭资源
        is.close();
        excel.close();
    }

    private static void write() throws IOException {
        //文件对象
        XSSFWorkbook excel = new XSSFWorkbook();
        //创建sheet页
        XSSFSheet sheet = excel.createSheet();

        //创建第一行
        XSSFRow row1 = sheet.createRow(0);
        //创建单元格
        row1.createCell(0).setCellValue("序号");
        row1.createCell(1).setCellValue("姓名");
        row1.createCell(2).setCellValue("城市");

        //创建第二行
        XSSFRow row2 = sheet.createRow(1);
        //创建单元格
        row2.createCell(0).setCellValue("1");
        row2.createCell(1).setCellValue("张三");
        row2.createCell(2).setCellValue("广东");

        //创建第三行
        XSSFRow row3 = sheet.createRow(2);
        //创建单元格
        row3.createCell(0).setCellValue("2");
        row3.createCell(1).setCellValue("李四");
        row3.createCell(2).setCellValue("湖南");

        //将excel文件写入到磁盘上
        FileOutputStream os = new FileOutputStream("D://poi_excel.xlsx");
        excel.write(os);
        //关闭资源
        os.close();
        excel.close();
    }
}
